package com.cdut.config;

import com.cdut.pojo.User;
import com.cdut.service.UserService;
import com.cdut.util.JsonResponce;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Arrays;

/**
 * author: xinmu
 * date: 2022/4/21
 * time: 23:45
 */


//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserService userService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        Subject subject = SecurityUtils.getSubject();
        logger.info("执行了=>授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:login");
        return null;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info("正在执行认证");


        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        logger.info(userToken.getUsername()+ Arrays.toString(userToken.getPassword()));

        //从数据库查询用户
        JsonResponce<User> userJsonResponce = userService.queryUserByName(userToken.getUsername());

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        logger.info(userJsonResponce.getData().getUsername());
        User loginUser = userJsonResponce.getData();

        //如果user查不到
        if (userJsonResponce.getData()==null){
            return null;//查不到
        }
        session.setAttribute("loginUser",userJsonResponce.getData());
        logger.info("[userRealm]"+"已经存放session"+userJsonResponce.getData());

        //密码认证 shiro做
        return new SimpleAuthenticationInfo(loginUser,userJsonResponce.getData().getPassword(),"");
    }
}
